import { AuditOutlined, FileTextOutlined, ClockCircleOutlined ,SearchOutlined,SyncOutlined} from '@ant-design/icons'
import {Card, Drawer, Table, Tag, message, Modal, Form, Select, Input, Button} from 'antd'
import React, { useState, useEffect } from 'react'
import '../../../DepartmentManage/views/style.css'
import EntranceApproval from './EntranceApproval'
import { useRequest } from '@umijs/hooks'
import { fetchRequest } from '../../../../utils/Request'
import { url } from '../../../../utils/url'
import { useDispatch, useSelector } from 'react-redux'
import actionTypes from '../../actionTypes'
import { getOriginString } from '../../../../utils/encrypt'
import moment from 'moment'


const tabList = [
    {
        key: '2',
        tab: '待审核',
    },
    {
        key: '3',
        tab: '审核不通过',
    },
    {
        key: '1',
        tab: '已生效',
    }, {
        key: "5",
        tab: "已失效"
    }
];

interface RequestParams {
    studentName:string,
    state: number,
    page: number,
    size: number
}

interface Operation {
    visible: boolean,
    content: any
}

interface DenyInfo {
    visible: boolean,
    content: any
}

export default function EntranceAppovalingTable() {
    const columns = [{
        title: "姓名",
        dataIndex: "studentName",
        key: 'studentName'
    }, {
        title: "所属机构",
        dataIndex: "deptName",
        key: 'deptName'
    }, {
        title: "门禁状态",
        dataIndex: 'state',
        key: 'state',
        render: (text: number) => {
            switch (text) {
                case 1:
                    return <Tag color="#87d068">已生效</Tag>;
                case 2:
                    return <Tag color="#EB693E">待审核</Tag>;
                case 3:
                    return <Tag color="#f50">审核不通过</Tag>;
                case 4:
                    return <Tag color="#2db7f5">待推送</Tag>;
                case 5:
                    return <Tag color="#f50">已失效</Tag>;
                case 6:
                    return <Tag color="#f50">推送失败</Tag>;
            }

        }
    }, {
        title: "操作",
        render: (record: any) => {
            console.log("操作")
            console.log(record.state)
            return <span>
                <Tag style={record.state === 5? undefined : { display: 'none' }}
                     className="tags-hover" color="#f50"
                     icon={<ClockCircleOutlined />}
                     onClick={() => setdenyInfo({ visible: true, content: record })} >延期</Tag>
                <Tag className="tags-hover" color="#108ee9"
                     icon={record.state ===2?<AuditOutlined /> : <FileTextOutlined />}
                     onClick={() => setApproval({ visible: true, content: record })}>
                    {record.state === 2 ? '审核' : '查看'}</Tag></span>
        }
    }]

    // const [visible, setvisible] = useState(false)

    const [approval, setApproval] = useState<Operation>({ visible: false, content: null })

    const [params, setParams] = useState<RequestParams>({ studentName:"",state: 2, page: 1, size: 10 })


    const [denyInfo, setdenyInfo] = useState<DenyInfo>({ visible: false, content: null })

    const [denyHelp, setdenyHelp] = useState<undefined | string>(undefined)

    //当翻页变化的时候
    function onPageChange(page: number) {
        setParams({ ...params, page: page  })
    }

    //点击搜索按钮
    function handleFinish(values: any) {
        setParams({ ...params, studentName: values.userName})
    }

    function handleReset() {
        setParams({
            studentName:"",state: 2, page: 1, size: 10
        })

    }
    const disptatch = useDispatch()

    const tableData = useSelector((state: any) => {

        return state.entranceManage.entrancetableData
    })

    console.log("条数")
    console.log(tableData.count)
    //请求函数
    async function getTableData(params: RequestParams) {
        console.log(params)
        try {
            const json = await fetchRequest(url.GET_ACCESS_TABLE, params)

            if (json.success) {
                disptatch({ type: actionTypes.GET_ENTRANCE_TABLE, payload: {
                        data: json.data.rows, count: json.size,total:json.data.total } })
            } else {
                message.destroy();
                message.error(json.error);
                disptatch({ type: actionTypes.GET_ENTRANCE_TABLE, payload: { data: [], count: 0 } })
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message);
            disptatch({ type: actionTypes.GET_ENTRANCE_TABLE, payload: { data: [], count: 0 } })
        }
    }
    const [form] = Form.useForm()
//查询框
    const entrancesearchForm = (<Card className="search-form"> <Form form={form} layout="inline" initialValues={{ healthState: -1 }} onFinish={handleFinish} onReset={handleReset}>

        <Form.Item className="form-control-item" name="userName" label="姓名">
            <Input className="search-form-item" />
        </Form.Item>

        <Form.Item className="form-control-item"  >
            <Button key="1" type="primary" icon={<SearchOutlined />} htmlType="submit" style={{ marginRight: '8px' }}>搜索</Button>
            <Button key="2" icon={<SyncOutlined />} htmlType="reset">重置</Button>

        </Form.Item>

    </Form></Card>)
    //请求
    const getData = useRequest(getTableData, {
        manual: true,
        loadingDelay: 200
    });

    //监听参数变化就重新请求数据
    useEffect(() => {
        getData.run(params)
    }, [params])


    function onApproval() {
        setApproval({ ...approval, visible: false })
        // setParams({...params})
        if (tableData.count > params.size && tableData.count - 1 === (params.page+1) * 10) {
            setParams({ ...params, page: params.page  })
        } else {
            getData.run(params)
        }
    }

    const delay = useRequest(delayRequest, {
        manual: true,
        loadingDelay: 200
    })

    const [delayForm] = Form.useForm();

    return (
        <div>
            {entrancesearchForm}
            <Card style={{ margin: '20px'}}
                  headStyle={{ marginBottom: '24px' }}
                  bordered={false}
                  tabList={tabList}
                  activeTabKey={params.state.toString()}
                  onTabChange={key => {
                      setParams({ studentName:"",page: 1, size: 10, state: parseInt(key) })
                  }}
            >
                <Table
                    rowKey={record => record.accessCardId}
                    loading={getData.loading}
                    pagination={{ hideOnSinglePage: true, pageSize: params.size,
                        total: tableData.total,
                        onChange: onPageChange,
                        showSizeChanger: false, simple: true, current: params.page  }}
                    columns={columns}
                    dataSource={tableData.data}
                />

                <Drawer destroyOnClose width="70%" visible={approval.visible} onClose={() => setApproval({ ...approval, visible: false })} >
                    <EntranceApproval content={approval.content} onApproval={onApproval} />
                </Drawer>

                <Modal destroyOnClose confirmLoading={delay.loading} visible={denyInfo.visible} title="门禁卡延期" onCancel={() => setdenyInfo({ visible: false, content: null })} onOk={() => delayForm.submit()} >
                    <Form form={delayForm} onFinish={onDelay}>
                        <Form.Item help={denyHelp} label="延期时长" name="applyDate" rules={[{ required: true, message: "必须要选择延期时间!" }]} >
                            <Select onChange={handleDenyChange}>
                                <Select.Option value={1}>1个月</Select.Option>
                                <Select.Option value={3}>3个月</Select.Option>
                                <Select.Option value={6}>6个月</Select.Option>
                                <Select.Option value={12}>12个月</Select.Option>
                            </Select>
                        </Form.Item>
                    </Form>
                </Modal>
            </Card>
        </div>
    )


    //提交操作
    function onDelay(value: any) {
        // console.log(value)
        const params = {
            startDate: moment().format("YYYY-MM-DD"),
            endDate: moment().add("month", value.applyDate).format("YYYY-MM-DD"),
            accessCardId: denyInfo.content.accessCardId,
        }
        delay.run(params);
        console.log(params);
    }

    //延期操作
    async function delayRequest(param: any) {
        try {
            const json = await fetchRequest(url.DELAY_CARD_URL, param);
            if (json.success) {
                message.destroy();
                message.success("延期成功!");
                setdenyHelp(undefined);
                setdenyInfo({ ...denyInfo, visible: false });
                if (tableData.count > params.size && tableData.count - 1 === (params.page+1) * 10) {
                    setParams({ ...params, page: params.page  })
                } else {
                    getData.run(params)
                }
            } else {
                message.destroy();
                message.error(json.error);
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message);
        }
    }


    function handleDenyChange(value: number) {
        setdenyHelp(moment().format("YYYY-MM-DD") + "~" + moment().add("month", value).format("YYYY-MM-DD") + `(${value}个月)`)
    }
}